package com.wx.io.netty.demo;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.EventExecutorGroup;

import javax.lang.model.element.VariableElement;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author wangxun
 * @version 1.0
 * @description: TODO
 * @date 2021/1/5 4:46 下午
 */
public class MyInBound extends ChannelInboundHandlerAdapter {

    AtomicInteger id = new AtomicInteger(0);
    /**
     * 当发生读事件的时候就会调用此方法
     * @param ctx 通道上下文
     * @param msg 附带信息
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        // 发送过来的内容
        ByteBuf byteBuf = (ByteBuf)msg;
        int size = byteBuf.writerIndex();
        byte[] bytes = new byte[size];
        byteBuf.getBytes(0,bytes);
        String content = new String(bytes);
        System.out.println(content);
        id.incrementAndGet();
        byteBuf.clear();
        byteBuf.writeBytes(id.toString().getBytes());
        ctx.write(byteBuf);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        System.out.println("client is closed");
        super.channelUnregistered(ctx);
    }
}
